package net.onceface.core.domain;

import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NoResultException;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import net.onceface.infra.domain.AbstractEntity;

/**
 * 商品图片
 * ***/
@Entity
@Table(name = "SYS_PRODUCT_PICTURE")
public class ProductPicture extends AbstractEntity{

	/**
	 * 
	 */
	private static final long serialVersionUID = 299210015660653967L;
	
	@Column(name = "PRODUCT_ID")
	private Long productId;
	
	@Column(name = "ADDRESS")
	private String address;
	
	@Column(name = "IS_DEFAULT")
	private boolean isDefaultPic;
	
	@Column( name = "UPLOAD_OWER")
	private String uploadOwer;
	
	@Column(name = "CREATE_DATE", nullable = false ,updatable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date createDate;

	public Long getProductId() {
		return productId;
	}

	public void setProductId(Long productId) {
		this.productId = productId;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getUploadOwer() {
		return uploadOwer;
	}

	public void setUploadOwer(String uploadOwer) {
		this.uploadOwer = uploadOwer;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public boolean isDefaultPic() {
		return isDefaultPic;
	}

	public void setDefaultPic(boolean isDefault) {
		this.isDefaultPic = isDefault;
	}

	public static List<ProductPicture> findByProductId(Long id) {
		try {
			return getRepository()
					.createJpqlQuery(
							"select m from ProductPicture m where m.productId=:productId order by m.isDefaultPic desc")
					.addParameter("productId", id).list();
		}catch(NoResultException e){
			return null;
		}
	}
	
	/**
	 * 传入商品ID,图片ID 重置默认图片
	 * **/
	public static void resetAllDefaultPicture(Long id, Long picId){
		List<ProductPicture> list = findByProductId(id);
		for(int i = 0; i < list.size(); i++){
			if(list.get(i).isDefaultPic()){
				list.get(i).setDefaultPic(false);
				list.get(i).save();
			}
			if(list.get(i).getId() == picId){
				list.get(i).setDefaultPic(true);
				list.get(i).save();
			}
		}
	}
	
	@Override
	public String[] businessKeys() {
		// TODO Auto-generated method stub
		return null;
	}

}
